package cn.dianchiyun.protocol.netty.dtu.entity;

import cn.dianchiyun.protocol.netty.utils.CRC16;
import cn.dianchiyun.protocol.netty.utils.HexUtil;
import org.apache.commons.lang.ArrayUtils;

/**
 * 写数据
 */
public class DTUWrite {

	//从机地址
	private String address;

	//功能码
	private String funCode;

	//寄存器地址
	private Integer registerAddress;

	//寄存器数量
	private Integer registerNum;

	//	CRC16校验和
	private byte[] crc16;

	public DTUWrite() {

	}

	public DTUWrite(String address, String funCode, Integer registerAddress, Integer registerNum) {
		super();
		this.address = address;
		this.funCode = funCode;
		this.registerAddress = registerAddress;
		this.registerNum = registerNum;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public String getFunCode() {
		return funCode;
	}

	public void setFunCode(String funCode) {
		this.funCode = funCode;
	}

	public Integer getRegisterAddress() {
		return registerAddress;
	}

	public void setRegisterAddress(Integer registerAddress) {
		this.registerAddress = registerAddress;
	}

	public Integer getRegisterNum() {
		return registerNum;
	}

	public void setRegisterNum(Integer registerNum) {
		this.registerNum = registerNum;
	}

	public byte[] getCrc16() {
		return crc16;
	}

	public void setCrc16(byte[] crc16) {
		this.crc16 = crc16;
	}

	public byte[] getBytes(){
		byte[] res = {};
		res = ArrayUtils.addAll(res, this.getAddress().getBytes());
		res = ArrayUtils.addAll(res, this.getFunCode().getBytes());
		res = ArrayUtils.addAll(res, HexUtil.intToHex16(this.getRegisterAddress()).getBytes());
		res = ArrayUtils.addAll(res, HexUtil.intToHex16(this.getRegisterNum()).getBytes());
		return res;
	}

	public String getString(){
		StringBuilder res = new StringBuilder();
		res.append(this.getAddress());
		res.append(this.getFunCode());
		res.append(HexUtil.intToHex16(this.getRegisterAddress()));
		res.append(HexUtil.intToHex16(this.getRegisterNum()));
		return res.toString();
	}

	public String getCRCString(){
		//System.out.println("getCRCBytes():" + getString());
		byte[] sbuf = CRC16.getSendBuf(getString());
		return CRC16.getBufHexStr(sbuf);
	}

	public static void main(String[] args) {
		DTUWrite dtuWrite = new DTUWrite("01", "04", 0, 11);
		System.out.println(dtuWrite.getString());
		System.out.println(new String(dtuWrite.getBytes()));

		System.out.println(dtuWrite.getCRCString());


		/*System.out.println(Integer.toHexString((256 & 0x000000FF) | 0xFFFFFF00 ).substring(4).toUpperCase());
		System.out.println(Integer.toHexString(10));
		System.out.println(Integer.valueOf("0a", 16 ));
		System.out.println("-1 hex  : 0x" + Integer.toString(-6, 16));*/

		//System.out.println(HexUtil.convertStringToHex("0000"));
	}

}
